﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<json/json.h>
#include<QDebug>
#include<QSqlQuery>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    m_faceDetect = make_shared<faceDetect>(m_db);
    m_proComImg = make_shared<proComImg>(m_faceDetect);
    m_comThread = make_shared<comsumePro>(m_proComImg);
    m_proThread = make_shared<producePro>(m_proComImg);
    m_detectThread = make_shared<detectPro>(m_proComImg);
    m_printPixMap = make_shared<PrintQPixMap>(m_proComImg);
    //图片获取
    void(proComImg::*image)(Mat) = &proComImg::getImage;
    connect(m_proComImg.get(),image,m_printPixMap.get(),&PrintQPixMap::showImage);
    //图片显示
    void(PrintQPixMap::*showUp)(QPixmap) = &PrintQPixMap::printImg;
    connect(m_printPixMap.get(),showUp,this,&MainWindow::showUp);
    //识别显示信息
    void(proComImg::*showeDetectFaceInfo)(QString,QString) = &proComImg::detectFace;
    connect(m_proComImg.get(),showeDetectFaceInfo,this,&MainWindow::showDetectFaceInfo);
    m_comThread->start();
    m_proThread->start();
    m_detectThread->start();

    initDataBase();

    ui->setupUi(this);
    ui->pushButton_right_wrong->setVisible(false);
    initTreeWidget();
    //单击显示信息
    connect(ui->treeWidget,&QTreeWidget::itemSelectionChanged,this,&MainWindow::showFaceDetails);


}
void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    int x1 = ui->widget_camera->pos().x();
    int y1 = ui->widget_camera->pos().y();
    painter.drawPixmap(x1,y1,ui->widget_camera->width(),ui->widget_camera->height(),m_picture);
}

void MainWindow::initTreeWidget()
{
    ui->treeWidget->clear();
    Json::Value json_group_res;
    m_faceDetect->groupGetlist(json_group_res,0,100);
    cout << json_group_res << endl;
    Json::Value group_id_list = json_group_res["result"]["group_id_list"];
    QList<QTreeWidgetItem *> rootItem;
    for(int i=0;i<group_id_list.size();i++)
    {
        QThread::msleep(500);
        QTreeWidgetItem *groupItem = new QTreeWidgetItem(ui->treeWidget,QStringList(QString(group_id_list[i].asString().c_str())));
        Json::Value Json_user_res;
        //qDebug() << group_id_list[i].asString().c_str() << endl;
        m_faceDetect->groupGetusers(Json_user_res,group_id_list[i].asString());
        cout << Json_user_res << endl;
        Json::Value user_id_list = Json_user_res["result"]["user_id_list"];
        for(int j=0;j<user_id_list.size();j++)
        {
            QTreeWidgetItem *userItem = new QTreeWidgetItem(groupItem,QStringList(QString(user_id_list[j].asString().c_str())));
            groupItem->addChild(userItem);
        }
        rootItem.append(groupItem);
        ui->treeWidget->insertTopLevelItem(0,groupItem);
    }
}

void MainWindow::initDataBase()
{
    m_db  = make_shared<QSqlDatabase>(QSqlDatabase::addDatabase("QMYSQL"));
    m_db->setHostName("127.0.0.1");
    m_db->setUserName("root");
    m_db->setPassword("123456");
    m_db->setDatabaseName("face_detect");
    if(!m_db->open())
    {
        QMessageBox::warning(this,"错误",m_db->lastError().text());
        return ;
    }
    else
    {
        qDebug() << "db setok !" << endl;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showUp(QPixmap pixMap)
{
    this->m_picture =pixMap;
    update();
}

void MainWindow::showFaceDetails()
{

    ui->label_image->clear();
    QList<QTreeWidgetItem *> selectItemList = ui->treeWidget->selectedItems();
    QTreeWidgetItem *selectItem = selectItemList[0];
    QTreeWidgetItem * root = selectItem->parent();
    if(root)
    {
        qDebug() <<"root : " <<root->text(0) << "selectIte : " << selectItem->text(0) << endl;
        QSqlQuery query("select * from user_table where group_id = ? and user_id = ?");
        query.bindValue(0,root->text(0));
        query.bindValue(1,selectItem->text(0));
        query.exec();
        QSqlError sqlError = query.lastError();
        qDebug() << sqlError << endl;
        while (query.next())
        {
                QString country = query.value(0).toString();
                qDebug() << "group_id : " << query.value(0).toString() << endl;
                qDebug() << "user_id : " << query.value(1).toString() << endl;
                qDebug() << "user_info : " << query.value(2).toString() << endl;
                qDebug() << "detect_quality : " << query.value(3).toString() << endl;
                qDebug() << "ctime : " << query.value(5).toString() << endl;
                QPixmap photo;
                photo.loadFromData(query.value(4).toByteArray());
                ui->lineEdit_group_id->setText(query.value(0).toString());
                ui->lineEdit_user_id->setText(query.value(1).toString());
                ui->textEdit_user_info->setText(query.value(2).toString());
                ui->comboBox_detect_quality->setEditText(query.value(3).toString());
                ui->label_image->setPixmap(photo);

        }
    }

}

void MainWindow::on_detectFace_clicked()
{
    if(m_proComImg->getIsDetect() == true)
    {
        qDebug() << "turn true" << endl;
        m_proComImg->setIsDetect(false);
    }
    else if(m_proComImg->getIsDetect() == false)
    {
        qDebug() << "turn false" << endl;
        m_proComImg->setIsDetect(true);
    }
}

void MainWindow::on_pushButton_add_user_clicked()
{
    addFace *addwidget = new addFace(m_db,m_faceDetect);
    void(addFace::*addFaceItems)(QString,QString) = &addFace::addTreeItems;
    connect(addwidget,addFaceItems,this,&MainWindow::addUser);
    addwidget->show();
}

void MainWindow::on_pushButton_delete_user_clicked()
{

    QList<QTreeWidgetItem*> selectItems = ui->treeWidget->selectedItems();
    for(int i=0;i<selectItems.size();i++)
    {
        if(selectItems[i]->parent() == NULL) continue;
        else
        {
            QTreeWidgetItem* group_id = selectItems[i]->parent();
            QTreeWidgetItem* user_id = selectItems[i];
            if(m_db->transaction())
            {
                QSqlQuery query("delete from user_table where user_id = ? and group_id = ?");
                query.bindValue(0,user_id->text(0));
                query.bindValue(1,group_id->text(0));
                query.exec();
                QSqlError sqlError = query.lastError();
                if(sqlError.type()  == QSqlError::NoError)
                {
                    Json::Value json_res;
                    m_faceDetect->userDelete(json_res,group_id->text(0).toStdString(),user_id->text(0).toStdString());
                    if(json_res["error_code"].asInt()!= 0)
                    {
                        m_db->rollback();
                    }
                    else
                    {
                        selectItems[i]->parent()->removeChild(ui->treeWidget->currentItem());
                        m_db->commit();
                    }
                    string res = "code :" + json_res["error_code"].asString() +"msg :" +json_res["error_msg"].asString();
                    QMessageBox *message = new QMessageBox(
                                QMessageBox::NoIcon,
                            "调用信息", QString(res.c_str()),
                            QMessageBox::Yes, NULL);
                    message->show();
                }
            }

        }
    }
}

void MainWindow::addUser(QString group_id,QString user_id)
{
    int flag = 0;
    int num = ui->treeWidget->topLevelItemCount();
    for(int i=0;i<num;i++)
    {
        QTreeWidgetItem *group_id_item = ui->treeWidget->topLevelItem(i);
        if(group_id_item->text(0) == group_id)
        {
            flag =1;
            QTreeWidgetItem *user_id_item = new QTreeWidgetItem;
            int userNum= group_id_item->columnCount();
            user_id_item->setText(userNum-1,user_id);
            group_id_item->addChild(user_id_item);
            break;
        }
    }
    if(flag == 0)
    {
        QTreeWidgetItem *group_id_item = new QTreeWidgetItem;
        group_id_item->setText(0,group_id);
        QTreeWidgetItem *user_id_item = new QTreeWidgetItem;
        user_id_item->setText(0,user_id);
        group_id_item->addChild(user_id_item);
        ui->treeWidget->insertTopLevelItem(ui->treeWidget->columnCount()-1,group_id_item);
    }
}

void MainWindow::on_pushButton_delete_face_group_clicked()
{
    QList<QTreeWidgetItem*> selectItems = ui->treeWidget->selectedItems();
    for(int i=0;i<selectItems.size();i++)
    {
        if(selectItems[i]->parent() != NULL) continue;
        else
        {
            qDebug() << "i ::  " << i << endl;
            QTreeWidgetItem* group_id = selectItems[i];
            if(m_db->transaction())
            {
                QSqlQuery query("delete from user_table where group_id = ?");
                query.bindValue(0,group_id->text(0));
                query.exec();
                QSqlError sqlError = query.lastError();
                if(sqlError.type()  == QSqlError::NoError)
                {
                    Json::Value json_res;
                    m_faceDetect->groupDelete(json_res,group_id->text(0).toStdString());
                    if(json_res["error_code"].asInt()!= 0)
                    {
                        m_db->rollback();
                    }
                    else
                    {
                        qDebug() << selectItems.size() << endl;
                        delete(group_id);
                        m_db->commit();
                    }
                    string res = "code :" + json_res["error_code"].asString() +"msg :" +json_res["error_msg"].asString();
                    QMessageBox *message = new QMessageBox(
                                QMessageBox::NoIcon,
                            "调用信息", QString(res.c_str()),
                            QMessageBox::Yes, NULL);
                    message->show();
                }
            }

        }
    }
}

void MainWindow::showDetectFaceInfo(QString group_id,QString user_id)
{
    qDebug() << "group_id2 : " <<group_id  << "user_id2 : " << user_id << endl;
    ui->label_image->clear();
    QSqlQuery query("select * from user_table where group_id = ? and user_id = ?");
    query.bindValue(0,group_id);
    query.bindValue(1,user_id);
    query.exec();
    QSqlError sqlError = query.lastError();
    qDebug() << sqlError << endl;
    while (query.next())
    {
            QString country = query.value(0).toString();
            qDebug() << "group_id : " << query.value(0).toString() << endl;
            qDebug() << "user_id : " << query.value(1).toString() << endl;
            qDebug() << "user_info : " << query.value(2).toString() << endl;
            qDebug() << "detect_quality : " << query.value(3).toString() << endl;
            qDebug() << "ctime : " << query.value(5).toString() << endl;
            QPixmap photo;
            photo.loadFromData(query.value(4).toByteArray());
            ui->lineEdit_group_id->setText(query.value(0).toString());
            ui->lineEdit_user_id->setText(query.value(1).toString());
            ui->textEdit_user_info->setText(query.value(2).toString());
            ui->comboBox_detect_quality->setEditText(query.value(3).toString());
            ui->label_image->setPixmap(photo);
            ui->pushButton_right_wrong->setVisible(true);
            ui->pushButton_right_wrong->setText("√");
            ui->pushButton_right_wrong->setStyleSheet("background:rgb(138, 226, 52)");
            QTreeWidgetItem *chooseItem;
            int num = ui->treeWidget->columnCount();
            for(int i=0;i<num;i++)
            {
                if(ui->treeWidget->topLevelItem(i)->text(0) == query.value(0))
                {
                    QTreeWidgetItem *temp = ui->treeWidget->topLevelItem(i);
                    int num2 = temp->columnCount();
                    for(int j=0;j<num2;j++)
                    {
                        if(temp->child(i)->text(0) == query.value(1))
                        {
                            chooseItem = temp->child(i);
                        }
                    }
                }
            }
            ui->treeWidget->setCurrentItem(chooseItem);
    }

}
